package com.lele.controller;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lele.pojo.Book;

import com.lele.util.*;


@WebServlet("/main")
public class selectAllBooks extends HttpServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Connection conn = null;
        PreparedStatement pstmt = null;
        ResultSet rs=null;
        List<Book> list=new ArrayList<>();
        try {
            conn = JDBCUtils.getConnection();
            String sql = "select * from books";
            pstmt = conn.prepareStatement(sql);
            
            rs= pstmt.executeQuery();
            while(rs.next()) {
            	String bookid = rs.getString(1);
                String title = rs.getString(2);
                String author = rs.getString(3);
                String publisher = rs.getString(4);
                double price = rs.getDouble(5);
                Book b=new Book();
                b.setBookid(bookid);
                b.setTitle(title);
                b.setAuthor(author);
                b.setPublisher(publisher);
                b.setPrice(price);
                list.add(b);
            }
            request.setAttribute("list", list);
            request.getRequestDispatcher("index.jsp").forward(request, response);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            //6. 释放资源
            JDBCUtils.close(rs,pstmt,conn);
        }
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
